package com.fruitshop.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Base64;

/**
 * 微信工具类
 */
@Slf4j
@Component
public class WxUtil {
    
    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    
    /**
     * 解密微信手机号
     *
     * @param sessionKey    会话密钥
     * @param encryptedData 加密数据
     * @param iv           加密算法的初始向量
     * @return 解密后的手机号信息JSON字符串
     */
    public String decryptPhoneNumber(String sessionKey, String encryptedData, String iv) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(sessionKey);
        byte[] ivBytes = Base64.getDecoder().decode(iv);
        byte[] dataBytes = Base64.getDecoder().decode(encryptedData);
        
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(ivBytes));
        
        cipher.init(Cipher.DECRYPT_MODE, keySpec, params);
        byte[] decryptedData = cipher.doFinal(dataBytes);
        
        return new String(decryptedData);
    }
} 